package ltd.dujiabao.springcloud.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import io.swagger.annotations.Api;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import ltd.dujiabao.springcloud.service.CircuitBreakerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author : DuJiabao
 * @Project : springcloud
 * @Time : 2021/5/22 20:50
 * @Desc :
 */
@Slf4j
@RestController
@Api("CircuitBreaker")
@RequestMapping("/circuitBreaker")
public class CircuitBreakerController {
  @Autowired
  CircuitBreakerService circuitBreakerService;

  @GetMapping("/{id}")
  public String paymentCircuitBreaker(@PathVariable("id") Integer id) {
    String result = circuitBreakerService.paymentCircuitBreaker(id);
    log.info("返回结果为： " + result);
    return result;
  }

  @HystrixCommand(fallbackMethod = "divFallback", commandProperties = {
          @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
          @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
          @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
          @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),
  })
  @GetMapping("/div/{i}")
  public String div(@PathVariable("i") Integer i) {
    int result = 10 / i;
    log.info("result: " + result);
    return Integer.toString(result);
  }

  public String divFallback(Integer i) {
    return "服务已经被我熔断！";
  }
}
